<template>
  <div class="container">
    <div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form ref="form" :model="form">
            <el-form-item label="公司名称：">
              <el-input
                style="width: 180px"
                v-model="form.CompanyName"
              ></el-input>
            </el-form-item>
            <el-form-item label="车辆名称：">
              <el-input
                style="width: 180px"
                v-model="form.LICENSE_PLATE"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-form ref="form" :model="form">
            <el-form-item label="开始日期：">
              <el-date-picker
                v-model="form.StartDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="结束日期：">
              <el-date-picker
                v-model="form.EndDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-form ref="form" :model="form" style="float: left">
            <el-button size="mini" type="primary" @click="getlistdata"
              >查 询</el-button
            >
            <el-button size="mini" type="success" @click="addLine"
              >新 增</el-button
            >
            <el-button style="padding: 0; border: 0">
              <el-upload
                action="/上传文件的接口"
                :on-change="onChange"
                :auto-upload="false"
                :show-file-list="false"
                accept=".xls, .xlsx"
                class="upload"
              >
                <el-button size="mini" type="success">导 入</el-button>
              </el-upload>
            </el-button>
            <el-button size="mini" type="success" @click="exportExcel"
              >导 出</el-button
            >
          </el-form>
        </el-col>
      </el-row>
    </div>
    <el-table
      highlight-current-row
      v-loading="loading"
      :data="
        tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
      "
    >
      <el-table-column
        prop="LineName"
        label="路线名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="LICENSE_PLATE"
        label="车辆牌照"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="CompanyName"
        label="公司名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="StartPointName"
        label="开始地点名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="EndPointName"
        label="结束地点名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="StartTime"
        label="路线开始时间"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="EndTime"
        label="路线结束时间"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="StatusStr"
        label="状态"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button type="text" @click="showMapDialog(scope.$index, scope.row)"
            >查看路线</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>

    <!-- 弹出框 添加路线 -->
    <el-dialog
      :title="addLineDialogTitle"
      :visible.sync="addLineDialogShow"
      width="50%"
    >
      <el-form
        ref="formLine"
        :model="formLine"
        label-width="120px"
        class="flex"
      >
        <el-form-item label="路线名称：">
          <el-input v-model="formLine.LineName"></el-input>
        </el-form-item>
        <el-form-item label="车辆：">
          <el-select
            style="width: 177px"
            v-model="formLine.VID"
            :options="arrayCar"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in arrayCar"
              :key="item.VID"
              :label="item.LICENSE_PLATE"
              :value="item.VID"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间：">
          <el-time-picker
            editable
            value-format="HH:mm"
            format="HH:mm"
            v-model="formLine.StartTime"
            :picker-options="{
              selectableRange: '00:00:00 - 23:59:00',
            }"
            placeholder="请输入开始时间"
          >
          </el-time-picker>
        </el-form-item>
        <el-form-item label="结束时间：">
          <el-time-picker
            editable
            value-format="HH:mm"
            format="HH:mm"
            v-model="formLine.EndTime"
            :picker-options="{
              selectableRange: '00:00:00 - 23:59:00',
            }"
            placeholder="请输入结束时间"
          >
          </el-time-picker>
        </el-form-item>

        <el-form-item label="出发位置：">
          <el-select
            style="width: 177px"
            v-model="formLine.StartPoint"
            :options="arrayGD"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in arrayGD"
              :key="item.PID"
              :label="item.PointName"
              :value="item.PID"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结束位置：">
          <el-select
            style="width: 177px"
            v-model="formLine.EndPoint"
            :options="arrayXNC"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in arrayXNC"
              :key="item.PID"
              :label="item.PointName"
              :value="item.PID"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-button
        type="success"
        style="float: right; margin: 20px"
        @click="openDialogAddPoint"
        >新增途径点</el-button
      >
      <el-table ref="tableLine"  :data="formLine.pointsData">
        <el-table-column
          prop="PathwayLNG"
          label="经度"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="PathwayLAT"
          label="纬度"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleEditPoint(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              @click="deletePoint(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addLineDialogShow = false">取 消</el-button>
        <el-button type="primary" @click="saveLine()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 弹出框 添加途径点 -->
    <el-dialog
      :title="addPointDialogTitle"
      :visible.sync="addPointDialogShow"
      width="50%"
    >
      <el-form
        ref="formPoint"
        :model="formPoint"
        label-width="140px"
        class="flex"
      >
        <el-form-item label="经度：">
          <el-input
            v-model="formPoint.PathwayLNG"
            placeholder="请输入经度"
          ></el-input>
        </el-form-item> 
        <el-form-item label="纬度：">
          <el-input v-model="formPoint.PathwayLAT" placeholder="请输入纬度"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addPointDialogShow = false">取 消</el-button>
        <el-button type="primary" @click="savePoint()"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 弹出框 从地图取点 -->
    <el-dialog
      :title="mapDialogTitle"
      :visible.sync="mapDialogShow"
      width="50%"
    >
      <div
        id="mapDialog"
        style="width: 90%; height: 400px; margin-left: 5%; margin-right: 5%"
      ></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="mapDialogShow = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import '@/assets/css/common.css'
import { formatDate } from '@/common/js/date.js'
import export2Excel from '@/utils/exportExcel/index.js'

export default {
  data () {
    return {
      currentPage: 1, //初始页
      pageSize: 10,    //    每页的数据
      loading: false,
      form: {
        StartDate: formatDate(new Date(new Date() - 3600 * 1000 * 24 * 30), 'yyyy-MM-dd'),
        EndDate: formatDate(new Date(), 'yyyy-MM-dd'),
        LICENSE_PLATE: '',
        CompanyName: '',
      },
      // teamList: [{ "CLIENT_NAME": "机扫车" }, { "CLIENT_NAME": "垃圾车" }],
      // teamValue: '机扫车',
      tableData: [],
      originalData: [],
      mapDialog: null,
      driving: null,
      mapDialogTitle: '',
      mapDialogShow: false,
      addLineDialogTitle: '',
      addLineDialogShow: false,
      addPointDialogTitle: '新增途径点',
      addPointDialogShow: false,
      formLine: {
        ID: '',
        LineName: '',
        StartTime: '05:00',
        EndTime: '23:00',
        VID: '',
        StartPoint: '',
        EndPoint: '',
        Roads: '',
        Status: '',
        pointsData: []
      },
      formPoint: {

      },
      arrayCar: [],
      arrayXNC: [],
      arrayGD: []
    }
  },
  created () {
    this.getGDData()
    this.getXNCData()
    this.getCarData()
    this.getlistdata()
  },
  methods: {
    async getGDData () {
      var url = 'Vehicle/GetPointInfoZT?Name=&Type=1&ClientNO=' + localStorage.getItem('CLIENT_NO')
      const { data } = await this.$Http.get(url)
      this.arrayGD = data
    },
    async getXNCData () {
      var url = 'Vehicle/GetPointInfoZT?Name=&Type=2&ClientNO=' + localStorage.getItem('CLIENT_NO')
      const { data } = await this.$Http.get(url)
      this.arrayXNC = data
    },
    async getlistdata () {
      this.currentPage = 1;
      this.loading = true
      var url = 'Vehicle/GetLineInfoZT?Client_NO=' + localStorage.getItem('CLIENT_NO') + '&Status=-1&StartTime=' + this.form.StartDate + '&EndTime=' + this.form.EndDate + ' 23:59:59'
      const { data } = await this.$Http.get(url)
      this.tableData = []
      data.forEach(element => {
        if (!element.LICENSE_PLATE.includes(this.form.LICENSE_PLATE)) {
          return;
        }
        if (!element.CompanyName.includes(this.form.CompanyName)) {
          return;
        }
        if (element.Status === '0') {
          element.StatusStr = '未过审'
        } else {
          element.StatusStr = '已过审'
        }
        // if (element.Roads.length > 0) {
        var arrlatlng = element.Roads.split(';')
        element.pointsData = []
        arrlatlng.forEach(b => {
          if (b.length > 0) {
            var latlng = b.split(',')
            if (latlng.length > 0) {
              element.pointsData.push({ 'PathwayLNG': latlng[0], 'PathwayLAT': latlng[1] })
            }
          }
        });
        // }
        this.tableData.push(element)
      });
      this.loading = false
    },

    async getCarData () {
      var url = 'Vehicle/GetVehicleInfoZT?CompanyName=&LicensePlate=&ClientNO=' + localStorage.getItem('CLIENT_NO')
      const { data } = await this.$Http.get(url)
      this.arrayCar = data
    },
    // 导出Excel
    exportExcel () {
      let excelName = '路线审批'
      // ：[ID]路线ID,[LineName]路线名称,[StartTime]路线开始时间,[EndTime]路线结束时间,
      // [VID]车辆ID,LICENSE_PLATE车辆牌照,CompanyName公司名称,[StartPoint]开始地点ID,[StartPointName] 开始地点名称,
      // [EndPoint]结束地点ID,[EndPointName]结束地点名称,[Roads]途径道路名称描述,[Status]状态（0未过审、1已过审）
      const filterVal = ['LineName', 'ID', 'StartTime', 'EndTime', 'LICENSE_PLATE', 'VID'
        , 'CompanyName', 'StartPoint', 'StartPointName', 'EndPoint', 'EndPointName', 'Roads', 'StatusStr']
      const tHeader = ['路线名称', '路线ID', '路线开始时间', '路线结束时间', '车辆牌照', '车辆ID'
        , '公司名称', '开始地点ID', '开始地点名称', '结束地点ID', '结束地点名称', '途径道路名称描述', '状态']
      export2Excel(tHeader, filterVal, this.tableData, excelName)
    },
    addLine () {
      this.addLineDialogTitle = '新增路线'
      this.addLineDialogShow = true
      this.formLine = {
        ID: '-1',
        LineName: '',
        StartTime: '05:00',
        EndTime: '23:00',
        VID: '',
        StartPoint: '',
        EndPoint: '',
        Roads: '',
        Status: '',
        pointsData: []
      }
    },
    async saveLine () {
      console.log(this.formLine)
      var strRoads = ''
            this.formLine.pointsData.forEach(element => {
        strRoads += element.PathwayLNG + ',' + element.PathwayLAT + ';'
      });
      var url = 'Vehicle/SaveLineInfoZT?ID=' + this.formLine.ID + '&Status=0&LineName=' + this.formLine.LineName + '&StartTime=' + this.formLine.StartTime + '&EndTime=' + this.formLine.EndTime +
        '&VID=' + this.formLine.VID + '&StartPoint=' + this.formLine.StartPoint + '&EndPoint=' + this.formLine.EndPoint + '&Roads=' + strRoads +
        '&ClientNO=' + localStorage.getItem('CLIENT_NO')
      const { data } = await this.$Http.get(url)
      if (data.IsSucess) {
        this.$message.success('新增成功');
        this.addLineDialogShow = false
        this.getlistdata()
      } else {
        this.$message.error('新增失败');
      }
    },
    //详情
    handleEdit (index, row) {
      this.addLineDialogTitle = '编辑路线'
      this.addLineDialogShow = true
      this.formLine = Object.assign({}, row);
    },
    openDialogAddPoint () {
      this.formPoint = {}
      this.addPointDialogTitle = '新增途径点'
      this.addPointDialogShow = true
    },
    savePoint () {
      if (this.addPointDialogTitle.includes('新增')) {
        this.formLine.pointsData.push(this.formPoint)
      }else{
        this.formLine.pointsData[this.formPoint.index] = this.formPoint
        // this.$refs.tableLine.refreshs();
      }
      this.addPointDialogShow = false
    },
    deletePoint (index, row) {
      this.formLine.pointsData.splice(index, 1);
    },
    handleEditPoint (index, row) {
      this.addPointDialogTitle = '编辑途径点'
      this.addPointDialogShow = true;
      this.formPoint = row
      this.formPoint.index = index;
    },
    showMapDialog (index, row) {
      this.mapDialogTitle = '查看' + row.LineName
      this.mapDialogShow = true;
      if (!this.mapDialog) {
        const _this = this
        setTimeout(() => {
          _this.mapDialog = new BMapGL.Map('mapDialog')// 创建Map实例
          _this.mapDialog.centerAndZoom("东丽区", 12);
          _this.mapDialog.enableScrollWheelZoom(true)//开启鼠标滚轮缩放
          _this.showPlan(row)
        }, 2000)// 延时3秒
      } else {
        this.showPlan(row)
      }
    },
    showPlan (row) {
      this.mapDialog.clearOverlays()
      if (!this.driving) {
        this.driving = new BMapGL.DrivingRouteLine(this.mapDialog, {
        renderOptions: {
          map: this.mapDialog,
          autoViewport: true,
          enableDragging: true,
        }
      })
      }
      this.driving.clearResults()
      var start = null;
      var end = null;
      this.arrayGD.forEach(element => {
        if (element.PID == row.StartPoint) {
          start = new BMapGL.Point(element.LONGITUDE, element.LATITUDE);
        }
      });
      this.arrayXNC.forEach(element => {
        if (element.PID == row.EndPoint) {
          end = new BMapGL.Point(element.LONGITUDE, element.LATITUDE);
        }
      });
      var wayPoint = []
      row.pointsData.forEach(element => {
        wayPoint.push(new BMapGL.Point(element.PathwayLNG, element.PathwayLAT))
      });
      this.driving.search(start, end
        , {
          waypoints: wayPoint
        }
      );
    },

    // 导入Excel
    onChange (file, fileList) {
      //  console.log(fileList);
      this.fileData = file; // 保存当前选择文件
      this.readExcel(); // 调用读取数据的方法
    },
    // 读取数据
    readExcel (e) {
      let that = this;
      const files = that.fileData;
      console.log(files);
      if (!files) {
        //如果没有文件
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader();
      console.log(fileReader)
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          //  console.log(ev.target)
          //  console.log(this);
          const workbook = this.XLSX.read(data, {
            type: "binary"// 以字符编码的方式解析
          });

          if (workbook.SheetNames.length >= 1) {
            //  this.$message({
            //    message: "导入数据表格成功",
            //    showClose: true,
            //    type: "success"
            //  });
            workbook.SheetNames.forEach(element => {
              console.log(element)
              // const wsname = element; //取第一张表
              // const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[element]); //生成json表格内容
              this.bulkLoad(this.XLSX.utils.sheet_to_json(workbook.Sheets[element]))
            });
            // console.log(ws)
            // this.inputExcelDataLength = ws.length
            // this.fullscreenLoading = this.$loading({
            //   lock: true,
            //   text: 'Loading',
            //   spinner: 'el-icon-loading',
            //   background: 'rgba(0, 0, 0, 0.7)'
            // })

          } else {
            this.$message.error("未读取到表格内容");
          }
        } catch (e) {
          console.log(e)
          return false;
        }
      };
      // 如果为原生 input 则应是 files[0]
      fileReader.readAsBinaryString(files.raw);
    },
    async bulkLoad (ws) {
      var item = ws[0]
      console.log(ws)
      console.log(item)
      var carStr = ''
      var StartPointStr = ''
      var EndPointStr = ''

      this.arrayCar.forEach(element => {
        if (item.CompanyName == element.COMPANY && item.LICENSE_PLATE == element.LICENSE_PLATE) {
          carStr = element.VID
        }
      });
      this.arrayGD.forEach(element => {
        if (item.StartPointName == element.PointName) {
          StartPointStr = element.PID
        }
      });
      this.arrayXNC.forEach(element => {
        if (item.EndPointName == element.PointName) {
          EndPointStr = element.PID
        }
      });
      this.formLine = {
        ID: '-1',
        LineName: item.LineName,
        StartTime: item.StartTime,
        EndTime: item.EndTime,
        VID: carStr,
        StartPoint: StartPointStr,
        EndPoint: EndPointStr,
        pointsData: ws,
      }
      // console.log(this.formLine)
      this.saveLine();
    },
    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage;
      // console.log(this.currentPage)
      // this.$set(this.query, 'pageIndex', val);
      // this.getData();
    },
    handleSizeChange (size) {
      this.pageSize = size;
      console.log(this.pageSize)
    }
  }
}
</script>
<style>
.content {
  overflow-y: scroll;
}
.el-col-6 {
  min-width: 400px;
  min-height: 50px;
}
.el-table th {
  height: 40px;
}
</style>